﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

using sgsBase;

namespace gaClear
{
	public enum UserReqTypes { Logon=1, Logoff=2, ChangePassword=3} 

	public enum UserResponseTypes
	{	LoggedIn = 1,	LoggedOut = 2,	UserNotRecognized = 3,	PasswordIncorrect = 4,
		PasswordChanged = 5, Other = 6 }


	public class LogonMsg : BaseMsg
	{
		//'Protected m_username As String
		protected string _password = "";
		protected UserReqTypes _requestType;
		protected string _newPassword = "";
		protected UserResponseTypes _response;
		#region properties
		public string Password
		{
			get { return _password; }
			set { _password = value; }
		}

		public string NewPassword
		{
			get { return _newPassword; }
			set { _newPassword = value; }
		}

		public UserReqTypes LogonType
		{
			get { return _requestType; }
			set { _requestType = value; }
		}
		public UserResponseTypes RespType
		{
			get { return _response; }
			set { _response = value; }
		}
		public string RequestTypeString
		{
			get { return _requestType.GetHashCode().ToString(); }
		}
		#endregion

		public LogonMsg()
		{
			IsCPC = false;
			ResponseType = "UserRsp";
		}

		protected override bool requestMsg(XmlTextWriter XmlW )
		{
			if (XmlW == null)
				return false;

			XmlW.WriteStartElement("FIXML");
			XmlW.WriteAttributeString("v", "5.0 SP2");
			XmlW.WriteAttributeString("s", "20090815");
			XmlW.WriteAttributeString("xv", "109");
			XmlW.WriteAttributeString("cv", "CME.0001");

			XmlW.WriteStartElement("UserReq");
			XmlW.WriteAttributeString("UserReqID", Globals.UserName+  "-" + UID);
			XmlW.WriteAttributeString("Username", Globals.UserName);

			if (LogonType != UserReqTypes.Logoff)
			{
				XmlW.WriteAttributeString("Password", _password);
			}

			if (LogonType == UserReqTypes.ChangePassword)
			{
				XmlW.WriteAttributeString("NewPassword", _newPassword);
			}

			XmlW.WriteAttributeString("UserReqTyp", RequestTypeString);

			XmlW.WriteStartElement("Hdr");
			XmlW.WriteAttributeString("TID", "CME");
			XmlW.WriteAttributeString("TSub", "CPAPI");
			XmlW.WriteAttributeString("SID", "1A3M"); //broker specific code
			XmlW.WriteAttributeString("SSub", Globals.UserName);

			XmlW.WriteEndElement();
			XmlW.WriteEndElement();
			XmlW.WriteEndElement();

			return true;
		}

		protected override void responseParse(XmlNode node)
		{
			base.responseParse(node);
			try
			{
			    _response = (UserResponseTypes)Enum.Parse(typeof(UserResponseTypes), getAttr(node, "UserStat"));
				_errMsg = getAttr(node, "UserStatText");

			    //' need to see if userstat = 2. if so, need to request a new password. 
			    //' UserStat="2" UserStatText="Password expired, please change your password and logon again"
			    if (_response == UserResponseTypes.LoggedOut)
				{
			        if (_errMsg.StartsWith("Password expired"))
					{
						SetNewPassword();
					}
			    }

			} 
			catch(Exception ex)
			{
				Email.SendError(ex);
			}
		}

		public void SetNewPassword()
		{
			DbUser usr = new DbUser();
			string currPass = "";
			string newpass = "";
			string ts = "";
			int pos = 0;
			int inc = 0;

			usr.UserId = 0;
			usr.Select();

			if (usr.NymxNewpass != "")
			{
				return;
			}
			currPass = usr.NymxPass;

			ts = currPass;

			while(ts != "" && !CASTHelper.IsNumeric(ts))
			{
			    ts = ts.Substring(1);
			    pos += 1;
			}
			inc = CASTHelper.Integer(ts);
			inc += 1;

			usr.NymxNewpass = currPass.Substring(0, pos) + inc;
			usr.Update();

			DbClearingTrade ct = new DbClearingTrade();
			ct.RefId = 0;
			ct.DtQueued = DateTime.Now;
			ct.ClearingHouse = 43;
			ct.ClearingBrokerId = 0;
			ct.ClearingStatus = 0;
			ct.BrokerDisplay = 1;
			ct.Insert();
		}
	}
}

#region old
//    '<FIXML v="4.4" s="20040109" r="20030618">
//    '      <UserReq UserReqID="gagcpcuser-1178044824265" Username="gagcpcuser" Password="gagcpcuser" UserReqTyp="1">
//    '            <Hdr TID="NYMEX" TSub="cpcapi"/>
//    '      </UserReq>
//    '</FIXML>

//    '## Logon response
//    '<FIXML v="4.4" s="20040109" r="20030618">
//    '      <UserRsp UserReqID="gagcpcuser-1178044824265" Username="gagcpcuser" UserStat="1">
//    '            <Hdr SID="NYMEX" SSub="cpcapi"/>
//    '      </UserRsp>
//    '</FIXML>

//    '<FIXML v="4.4" s="20040109" r="20030618">
//    '<UserReq UserReqID="UNIQUE-REQID" UserReqTyp="3" Username="USER"
//    'Password="********" NewPassword="nnnnnnnn">
//    '<Hdr TID="NYMEX" TSub="cpcapi"/>
//    '</UserReq>
//    '</FIXML>

//    'Protected m_username As String
//    Protected m_password As String
//    Protected m_requesttype As UserReqTypes
//    Protected m_newpassword As String
//    Protected m_response As UserResponseTypes

//#Region "Properties"
//    'Public Property UserName() As String
//    '	Get
//    '		Return m_username
//    '	End Get
//    '	Set(ByVal Value As String)
//    '		m_username = Value
//    '	End Set
//    'End Property

//    Public Property Password() As String
//        Get
//            Return m_password
//        End Get
//        Set(ByVal Value As String)
//            m_password = Value
//        End Set
//    End Property
//    Public Property NewPassword() As String
//        Get
//            Return m_newpassword
//        End Get
//        Set(ByVal Value As String)
//            m_newpassword = Value
//        End Set
//    End Property

//    Public Property LogonType() As UserReqTypes
//        Get
//            Return m_requesttype
//        End Get
//        Set(ByVal Value As UserReqTypes)
//            m_requesttype = Value
//        End Set
//    End Property

//    Public Property RespType() As UserResponseTypes
//        Get
//            Return m_response
//        End Get
//        Set(ByVal Value As UserResponseTypes)
//            m_response = Value
//        End Set
//    End Property

//    Public ReadOnly Property RequestTypeString() As String
//        Get
//            Return m_requesttype.GetHashCode.ToString()
//        End Get
//    End Property
//#End Region
	#endregion

